package com.DT.netTool;

import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import androidx.annotation.RequiresApi;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


public class PingNetUtil {
    private static final String TAG = PingNetUtil.class.getSimpleName();
    private static final boolean IS_DEBUG = true;
    private Process process = null;
    /**
     * //@param pingNetEntity 检测网络实体类
     */
    public boolean isRun(){
         if(process == null)
             return false;
         else
             return true;
    }
    public Process getProcess(){
        return process;
    }

    public void clearProcess(){
        int exitFlag=-1;
        while (exitFlag == -1) {
            try {
                exitFlag = process.exitValue();
            } catch (IllegalThreadStateException e) {//进程没有终止
                process.destroy();
            }
            Log.i("Ping--------","exitFlag:"+exitFlag);

        }
        Log.i("Ping--------","exitValue():"+process.exitValue());

        process=null;
    }
    public PingNetEntity ping(String pingIP, String pingCount, String pingWtime, Handler pingHandler) {


        PingNetEntity pingNetEntity=new PingNetEntity(pingIP,Integer.parseInt(pingCount.contains("-")? "0":pingCount),Integer.parseInt(pingWtime.contains("-")? "0":pingWtime));

        if (pingCount.contains("-"))pingCount="";
        else pingCount=" -c "+pingCount;


        if (pingWtime.contains("-"))pingWtime="";
        else pingWtime=" -w "+pingWtime;


        String line = null;

        BufferedReader successReader = null;
        String command = "ping " + pingCount + pingWtime + " " + pingIP;

        debugLog(command);

//        String command = "ping -c " + pingCount + " " + host;
        try {
            process = Runtime.getRuntime().exec(command);
            if (process == null) {
                debugLog( "ping fail:process is null.");
                append(pingNetEntity.getResultBuffer(), "ping fail:process is null.");
                pingNetEntity.setPingTime(null);
                pingNetEntity.setResult(false);
                return pingNetEntity;
            }
            successReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            while ((line = successReader.readLine()) != null) {
                debugLog( line);
                append(pingNetEntity.getResultBuffer(), line);
                /*发送到UI*/
                Message sendMsg=new Message();
                sendMsg.what=9999;
                sendMsg.obj=line+'\n';
                pingHandler.sendMessage(sendMsg);
                /*发送到UI*/
                String time;
                if ((time = getTime(line)) != null) {
                    pingNetEntity.setPingTime(time);
                }
            }

            try {
                process.exitValue();

            } catch (IllegalThreadStateException e) {//进程没有终止
                int status = process.waitFor();
                if (status == 0) {
                    debugLog("exec cmd success:" + command);
                    //                append(pingNetEntity.getResultBuffer(), "exec cmd success:" + command);
                    pingNetEntity.setResult(true);
                } else {
                    debugLog("exec cmd fail.");
                    //                append(pingNetEntity.getResultBuffer(), "exec cmd fail.");
                    pingNetEntity.setPingTime(null);
                    pingNetEntity.setResult(false);
                }
                debugLog( "exec cmd is running.");
            }

            debugLog( "exec finished.");
//            append(pingNetEntity.getResultBuffer(), "exec finished.");
        } catch (IOException e) {
            debugLog( String.valueOf(e));
        } catch (InterruptedException e) {
            debugLog( String.valueOf(e));
        } finally {
            debugLog( "ping exit.");
            if (process != null) {
                process.destroy();
            }
            if (successReader != null) {
                try {
                    successReader.close();
                } catch (IOException e) {
                    debugLog( String.valueOf(e));
                }
            }
        }
        debugLog( pingNetEntity.getResultBuffer().toString());
        return pingNetEntity;
    }

    private static void append(StringBuffer stringBuffer, String text) {
        if (stringBuffer != null) {
            stringBuffer.append(text + "\n");
        }
    }

     static String getTime(String line) {
        String[] lines = line.split("\n");
        String time = null;
        for (String l : lines) {
            if (!l.contains("time="))
                continue;
            int index = l.indexOf("time=");
            time = l.substring(index + "time=".length());
//            debugLog(time);
        }
        return time;
    }

    public static void debugLog(String content){
        if (IS_DEBUG){

            Log.d(TAG,content);
        }
    }
}
